
package com.huawei.saashousekeeper.interceptor;

import com.huawei.saashousekeeper.config.TenantConfigurer;

import lombok.extern.log4j.Log4j2;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.sql.Connection;

/**
 * mybatis拦截，获取connection
 *
 * @since 2022-02-14
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Log4j2
public class MybatisInterceptor implements Interceptor {

    @Autowired
    TenantConfigurer tenantConfigurer;

    @Override
    public Object intercept(Invocation invocation) throws Exception {

        Connection coon = (Connection) invocation.getArgs()[0];
        String schema = tenantConfigurer.getSchema();
        Assert.notNull(schema, "Routing failure, the Tenant‘schema is null");
        coon.setCatalog(schema);
        return invocation.proceed();
    }
}
